package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.img_path}")
    private  String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info("接收到的文件:{}", file);
        // 把文件转存到其他位置
        // 处理文件名
        // 先拿到原始文件名-- 为了拿到文件后缀
        String filename = file.getOriginalFilename();
        // 拿后缀
        String suffix = filename.substring(filename.lastIndexOf("."));  // 带.
        // 生成uuid  随机字符串
        String uuid = UUID.randomUUID().toString();
        String newFilename = uuid+suffix ;
        // 处理文件路径
        try {
            // 核心代码
            file.transferTo(new File(path+newFilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newFilename);
    }

    @GetMapping("/download")
    public void  download(String name, HttpServletResponse response){
        // jdk7 --->try resource
        try (FileInputStream fis = new FileInputStream(new File(path+name));
             ServletOutputStream sos = response.getOutputStream()){
//            // 输入流
//            FileInputStream fis = new FileInputStream(new File(path+name));
//            // 输出流
//            ServletOutputStream sos = response.getOutputStream();
            response.setContentType("image/jpeg");
            StreamUtils.copy(fis,sos);
            } catch (IOException e) {
              throw  new RuntimeException(e);
            }
    }
}
